package com.msh.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.msh.common.VMSystem;
import com.msh.entity.TaskCollectEntity;
import com.msh.entity.TaskEntity;
import com.msh.service.TaskCollectService;
import com.msh.service.TaskService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import net.sf.cglib.core.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * @author :zhangchuanfu
 * @Date :2023/2/6
 * @Time :21:58
 * @description :工单定时收集执行器
 */
@Component
public class TaskColletctJob {
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskCollectService taskCollectService;

    @XxlJob("taskCollecJobExcutor")
    public ReturnT<String> collectTask(String param) {
        TaskCollectEntity taskCollectEntity = new TaskCollectEntity();
        LocalDate start = LocalDate.now().plusDays(-1);
        //进行中的工单
        taskCollectEntity.setProgressCount(this.count(start, VMSystem.TASK_STATUS_PROGRESS));
        //取消或拒绝的工单
        taskCollectEntity.setCancelCount(this.count(start,VMSystem.TASK_STATUS_CANCEL));
        //完成的工单
        taskCollectEntity.setFinishCount(this.count(start,VMSystem.TASK_STATUS_FINISH));
        //日期
        taskCollectEntity.setCollectDate(start);
        //先删除数据，防止任务重复执行造成数据冗余
        clearData(start);
        taskCollectService.save(taskCollectEntity);
        cleanTask();
        return ReturnT.SUCCESS;
    }

    private void clearData(LocalDate start) {
        LambdaQueryWrapper<TaskCollectEntity> qw = new LambdaQueryWrapper<>();
        qw.eq(TaskCollectEntity::getCollectDate, start);
        taskCollectService.remove(qw);
    }

    /**
     * 按时间和状态进行统计
     * @param start
     * @param taskStatus
     * @return
     */
    private int count(LocalDate start, Integer taskStatus) {
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        qw.
                ge(TaskEntity::getUpdateTime,start)
                .lt(TaskEntity::getUpdateTime,start.plusDays(1))
                .eq(TaskEntity::getTaskStatus,taskStatus);
        return taskService.count(qw);
    }

    /**
     * 无效工单处理
     */
    private void cleanTask() {
        var um = new UpdateWrapper<TaskEntity>();

        um.lambda().lt(TaskEntity::getUpdateTime,LocalDate.now())
                .and(w->w.eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_CREATE).or().eq(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS))
                .set(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_FINISH)
                .set(TaskEntity::getDesc,"工单超时");
        taskService.update(um);
    }
}
